import { reqGoodsInfo } from "@/api/goods";
import { userBehavior } from "@/behaviors/userBehavior";
import { reqCartAdd, reqCartList } from "@/api/cart";
Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    goodsId: "",
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: "", // 祝福语
    btnState: 0, // 加入购物车是0，立即购买是1
    allCount: "", // 购物车总数量
  },

  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      btnState: 0,
    });
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      btnState: 1,
    });
  },

  // 弹窗 确定按钮
  async handlerSubmit() {
    const { token, count, blessing, btnState, goodsId } = this.data;
    // 如果没有登录，则跳转到登录页面
    if (!token) {
      wx.navigateTo({
        url: "/pages/login/login",
      });
      return;
    }

    if (btnState === 0) {
      // 点击的是 加入购物车按钮
      const { data } = await reqCartAdd({ goodsId, count, blessing });
      console.log("加入购物车=》", data);
      if (data.code === 200) {
        this.setData({
          show: false,
        });

        this.getGoodsCount();

        wx.showToast({ title: "加入购物车成功！", icon: "none" });
      }
    } else {
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`,
      });
    }
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false });
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    // console.log(event.detail);
    this.setData({
      count: event.detail,
    });
  },

  // 获取商品详情
  async getGoodsInfo() {
    const { data } = await reqGoodsInfo(this.data.goodsId);
    // console.log("获取商品详情=》", data);
    this.setData({
      goodsInfo: data.data,
    });
  },

  // 预览图片
  previewImage() {
    wx.previewImage({
      urls: this.data.goodsInfo.detailList, // 需要预览的图片http链接列表
    });
  },

  // 获取购物车总数量
  async getGoodsCount() {
    if (!this.data.token) {
      wx.showToast({ title: "请先登录！", icon: "none" });
      return;
    }
    const { data } = await reqCartList();
    // console.log("获取购物车总数量=》", data);
    let sum = 0;
    data.data.forEach((item) => {
      sum += item.count;
    });
    this.setData({
      allCount: sum > 99 ? "99+" : sum + "",
    });
  },

   // 转发功能
   onShareAppMessage(){
     return {
       title:"只为你怦然心动",
       path:'/pages/index/index',
       imageUrl:'../../../../../assets/images/love.jpg'
     }
   },

   // 分享朋友圈
   onShareTimeline() {
    return {
      title:"只为你怦然心动",
      path:'/pages/index/index',
      imageUrl:'../../../../../assets/images/love.jpg'
    }
   },

  onLoad(options) {
    this.data.goodsId = options.goodsId;
    this.getGoodsInfo();
    this.getGoodsCount();
  },
});
